import { useMutation, commitLocalUpdate } from "react-relay";
import {useCallback, useContext, useState} from "react";
import {
  ConnectionHandler,
  RecordSourceSelectorProxy,
  RecordProxy
} from "relay-runtime";
//import { DeviceCommonInput } from "./__generated__/useCreateDeviceMutation.graphql";
import {UserContext} from "../routing/UserContext";
import { useRemovePipingUnitMutation$data } from "./__generated__/useRemovePipingUnitMutation.graphql";
import {PipingUnitInput} from "./__generated__/useNewPipingUnitMutation.graphql";
import {useToast} from "customize-easy-ui-component";
import {useRelayEnvironment} from "react-relay/hooks";
import {RecordSourceProxy} from "relay-runtime/lib/store/RelayStoreTypes";

const graphql = require("babel-plugin-relay/macro");

//这个特别！返回{TodoEdge, User} 而不是直接返回TodoNode: Todo就可以了。!多出两个麻烦。
const mutation = graphql`
  mutation useRemovePipingUnitMutation($id: ID!) {
    removePipingUnit(id:$id) 
  }
`;

/**淘汰这个管道单元
 * */
export default function useRemovePipingUnitMutation() {
  const [called, setCalled] =useState<boolean>(false);
  const [result, setResult] =useState<any>('');
  const [commit, doing] = useMutation(mutation);
  const toast = useToast();
  // const environment = useRelayEnvironment();

  return {
    call:useCallback(
        (id: string,pid: string) => {
          let disposable= commit({
            variables: {
              id
            },
            updater: (store: RecordSourceSelectorProxy, data) => {
              const { removePipingUnit }= data as useRemovePipingUnitMutation$data;
              if(!removePipingUnit)  return;
              //不能嵌套更新relay store;
              //commitLocalUpdate(environment, storeMe => {  sharedUpdaterMe(storeMe, pid, id);   });
              //立刻更新页面：
              sharedUpdater(store, pid, id);
            },
            onCompleted: (response) => {
              setResult((response as any).removePipingUnit);
              toast({
                title: "后端应答",
                subtitle: '完成提交了，报告ID＝'+ id,
                intent: "info"
              });
            },
          });
          //必须放在commit函数之后的，才会doing逻辑=true生效,doing+called逻辑,保障同步化
          setCalled(true);
          return disposable;
        },
        [commit,toast]
    ),
    doing,
    result,
    called,
    reset: ()=>setCalled(false),
  };
}

//相对原来直接操作store + Query{}接口直接查询的方式：目前用node()关联父对象然后集合字段[List]的ConnectionHandler模式，就不需要传递查询接口的参数。
function sharedUpdater(
    store: RecordSourceSelectorProxy,
    parentId: string,
    deletedID: string
) {
  const fromObj = store.get(parentId);
  if (!fromObj) {
      return;
  }
  //对应父辈模型所关联的集合[List]属性字段， 其旁边所标注的@connection(key: "TodoList_todos")
  const connection = ConnectionHandler.getConnection(
      fromObj,
      "Pipeline_cell_list"
  );
  if (!connection) {
      return;
  }
  ConnectionHandler.deleteNode(connection, deletedID);
}

